package com.longtop.sp.mapdao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.longtop.sp.mapdao.dialect.oracle.FieldEntryList;
import com.longtop.sp.mapdao.impl.UUIDPrimaryGenerator;
import com.longtop.sp.mapdao.meta.IPrimaryKey;

public class PrimaryKeyHelper {
	private List<IPrimaryGenerator> primaryGenerators ;
//	= new ArrayList<IPrimaryGenerator>();
	
	public PrimaryKeyHelper () {
//		primaryGenerators.add(new UUIDPrimaryGenerator());
	}
	

	public void setPrimaryGenerators(List<IPrimaryGenerator> primaryGenerators) {
		this.primaryGenerators = primaryGenerators;
	}


	public void reBuildDataMap(IPrimaryKey pk, Map tmData) {

		for (int i = 0; i < pk.size(); i++) {
			String pkName = pk.getPrimaryKey(i);
			if (!tmData.containsKey(pkName) || tmData.get(pkName)== null) {
				// 表示没有设置主键
				tmData.put(pkName, "$NULL$");
			}
		}
	}

	public Map<String, Object> getPrimaryKey(IPrimaryKey pk,
			FieldEntryList fields) {
		Map pkMap = new HashMap<String, Object>();
		for (int i = 0; i < fields.getColumnCount(); i++) {
			String fieldName = fields.getFieldName(i);
			if (pk.isPrimaryKey(fieldName)) {
				String value = (String) fields.getFieldValue(i);
				if (value == null || "'$NULL$'".equalsIgnoreCase(value)) {
					pkMap.put(fieldName,
							buildPrimaryKey(fields.getFieldType(i)));
				}
			}
		}
		return pkMap;

	}

	private Serializable buildPrimaryKey(String fieldType) {
		for (IPrimaryGenerator primaryGenerator : primaryGenerators) {
			if (primaryGenerator != null && primaryGenerator.isMatch(fieldType)) {
				return primaryGenerator.genPK();
			}
		}
		return null;
	}
}